package com.snacks;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.snacks.data.Cache;
import com.snacks.data.URLconstan;
import com.snacks.utils.Base64;

public class Post extends Activity implements OnClickListener {
	private static final int CAPTURE_IMAGE_REQUEST_CODE = 2;
	private static final int SELECT_PICTURE = 1;
	private static String selectedImagepath="", createUser = "dungtt";
	private static String name, address, phone, description, strLocation, strCity, strDistrict;	
	
	private Button btSelectImage, btPost, btCamera, btLocation, btBack;
	private ImageView imageView;
	private EditText txtName, txtAddress, txtPhone, txtDescription,
			txtLocation;
	private Spinner spinnerCity, spinnerDistrict;
	private static int posCity;

	private TextView view_errorPost;

	private ProgressDialog dialog;
	private String encodeImage = "";
	private Bitmap myBitmap;
	public byte[] b;
	private int result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.post);

		txtName = (EditText) findViewById(R.id.edtName);
		txtAddress = (EditText) findViewById(R.id.edtAddress);
		txtPhone = (EditText) findViewById(R.id.edtPhone);
		txtDescription = (EditText) findViewById(R.id.edtDescription);
		txtLocation = (EditText) findViewById(R.id.edtLocation);

		view_errorPost = (TextView) findViewById(R.id.View_error_post);

		Bundle mCoordinates = getIntent().getExtras();
		if (mCoordinates != null) {
			strLocation = mCoordinates.getString("Toado");
			txtLocation.setText(strLocation);
		}
		
		btBack = (Button) findViewById(R.id.btBack);
		btBack.setOnClickListener(this);

		btLocation = (Button) findViewById(R.id.btlocation);
		btLocation.setOnClickListener(this);
		
		imageView = (ImageView) findViewById(R.id.previewImage);
		myBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_launcher);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
		b = stream.toByteArray();

		btSelectImage = (Button) findViewById(R.id.btBrowser);
		btSelectImage.setOnClickListener(this);
		
		btCamera = (Button) findViewById(R.id.btCamera);
		btCamera.setOnClickListener(this);

		btPost = (Button) findViewById(R.id.btPost);
		btPost.setOnClickListener(this);

		spinnerCity = (Spinner) findViewById(R.id.spinnerCity);
		spinnerDistrict = (Spinner) findViewById(R.id.spinnerDistrict);
		ArrayAdapter<CharSequence> adapterCity = ArrayAdapter
				.createFromResource(this, R.array.danhsachthanhpho,
						android.R.layout.simple_spinner_item);
		adapterCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerCity.setAdapter(adapterCity);
		spinnerCity.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View arg1,
					int pos, long id) {
				// TODO Auto-generated method stub
				posCity = pos;
				if (posCity >= 0)
					selectDistrict();
				strCity = parent.getItemAtPosition(pos).toString();

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		
		setValue();
		Log.d("Post", "name: " + name + ", address: " + address + ", phone: " + phone + ", selectedImagepath: " + selectedImagepath);
		
		// Nhan anh tu camera o activity main
		Bundle mBundle = getIntent().getExtras();

		if (mBundle != null) {
			selectedImagepath = mBundle.getString("imagePath");
			myBitmap = BitmapFactory.decodeFile(selectedImagepath);
			imageView.setImageBitmap(myBitmap);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btBrowser:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
			break;
		case R.id.btCamera:
			Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST_CODE);
			break;

		case R.id.btlocation:
			getValue();
			Intent mapIntent = new Intent(getBaseContext(), MapPost.class);
			startActivity(mapIntent);
			break;

		case R.id.btPost:
			getValue();			
			
			new SignUpTask().execute();			
			Log.i("Post new ", encodeImage);
			Log.i("Post", "name: " + name + ", address: " + address + ", phone: " + phone + ", location: " + strLocation);			
		
			break;
		case R.id.btBack:
			finish();
			break;
		default:
			break;
		}
	}
	
	private void getValue(){
		name = txtName.getText().toString().trim();
		address = txtAddress.getText().toString().trim();
		phone = txtPhone.getText().toString().trim();
		description = txtDescription.getText().toString().trim();		
	}
	
	private void setValue(){
		txtName.setText(name);
		txtAddress.setText(address);
		txtPhone.setText(phone);
		txtDescription.setText(description);
		if(selectedImagepath.length() > 0){
			myBitmap = BitmapFactory.decodeFile(selectedImagepath);
			imageView.setImageBitmap(myBitmap);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagepath = getPath(selectedImageUri);

				Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagepath);
				imageView.setImageBitmap(myBitmap);

				ByteArrayOutputStream stream = new ByteArrayOutputStream();				

				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
				b = stream.toByteArray();

				encodeImage = Base64.encodeBytes(b);				
			}
		}
		
		if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				
				// Xu ly anh da duoc chup
				Uri selectedImageUri = data.getData();
				selectedImagepath = getPath(selectedImageUri);
				Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagepath);
				imageView.setImageBitmap(myBitmap);

				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
				b = stream.toByteArray();
				
				encodeImage = Base64.encodeBytes(b);
				
			}
			if (resultCode == RESULT_CANCELED) {
				// Nguoi dung huy chup anh
			} else {
				// Loi xay ra khi chup anh
			}
		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private void ProcessPost(String name, String address, String phone,
			String description, String district, String location, String user,
			String thumbnail) {

		district = district.replace(" ", "_");
		district = district.trim();

		ArrayList<NameValuePair> rq = new ArrayList<NameValuePair>();
		rq.add(new BasicNameValuePair("name", name));
		rq.add(new BasicNameValuePair("address", address));
		rq.add(new BasicNameValuePair("phone", phone));
		rq.add(new BasicNameValuePair("description", description));
		rq.add(new BasicNameValuePair("area", district));
		rq.add(new BasicNameValuePair("user", user));
		rq.add(new BasicNameValuePair("thumbnail", thumbnail));
		rq.add(new BasicNameValuePair("coordinates", location));

		try {
			Log.i("Post", "Đang kết nối tới sever để đăng kí...");
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(URLconstan.getPostItemService());
			if (rq != null) {
				Log.i("Post", "Gửi đi Dữ liệu" + String.valueOf(rq));
				httppost.setEntity(new UrlEncodedFormEntity(rq));
			}
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			entity.getContent();
			Log.i("Post", entity.getContent().toString());
			Log.i("Post", "Đã  kết nối tới sever...");
		} catch (IOException e) {
			Log.e("Post", "Lỗi kết nối:" + e.toString());
		} catch (Exception e) {
			Log.e("Post", "Lỗi kết nối:" + e.toString());
		} finally {
			Intent mIntent = new Intent(Post.this, Home.class);
			startActivity(mIntent);
		}

	}

	// xu li spinner chon quan phu thuoc vao spinner chon thanh pho
	public void selectDistrict() {
		if (posCity == 0) {
			ArrayAdapter<CharSequence> adapterDistrict = ArrayAdapter
					.createFromResource(this, R.array.quan_hanoi,
							android.R.layout.simple_spinner_item);
			adapterDistrict
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerDistrict.setAdapter(adapterDistrict);
		}
		if (posCity == 1) {
			ArrayAdapter<CharSequence> adapterDistrict = ArrayAdapter
					.createFromResource(this, R.array.quan_hochiminh,
							android.R.layout.simple_spinner_item);
			adapterDistrict
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerDistrict.setAdapter(adapterDistrict);
		}
		if (posCity == 2) {
			ArrayAdapter<CharSequence> adapterDistrict = ArrayAdapter
					.createFromResource(this, R.array.quan_danang,
							android.R.layout.simple_spinner_item);
			adapterDistrict
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerDistrict.setAdapter(adapterDistrict);
		}		
		if (posCity == 4) {
			ArrayAdapter<CharSequence> adapterDistrict = ArrayAdapter
					.createFromResource(this, R.array.quan_haiphong,
							android.R.layout.simple_spinner_item);
			adapterDistrict
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerDistrict.setAdapter(adapterDistrict);
		}
		spinnerDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				strDistrict = arg0.getItemAtPosition(arg2).toString();
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}
	
	private void closeDialog() {
		this.dialog.dismiss();
	}

	private void showDialog() {
		this.dialog = ProgressDialog.show(Post.this, "Chờ trong giây lát", "Đang tải dữ liệu", true);
	}

	public void showMessage(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(Post.this);
		builder.setTitle(title);
		builder.setMessage(Html.fromHtml(message));
		builder.setCancelable(false);
		builder.setNegativeButton("Đồng ý",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						closeDialog();
						dialog.cancel();

					}
				});
		builder.show();
	}

	public void showMessageSuccess(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(Post.this);
		builder.setTitle(title);
		builder.setMessage(Html.fromHtml(message));
		builder.setCancelable(false);
		builder.setNegativeButton("Đăng nhập ngay",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						startActivity(new Intent().setClass(Post.this, Main.class));
					}
				});
		builder.show();
	}
	
	public void CheckSignUp() {	
		
		if (name.equals("")) {
			this.result = 1;		
		} else if (String.valueOf(address).equals("")) {
			this.result = 2;
		} else if (String.valueOf(strLocation).equals("")) {
			this.result = 3;
		} else if (String.valueOf(phone).equals("")) {
			this.result = 4;		
		} else if (String.valueOf(phone).length() < 8) {
			this.result = 5;
		} else if (String.valueOf(phone).length() > 12) {
			this.result = 5;
		}
		else {
			ProcessPost(name, address, phone, description, strDistrict, strLocation, createUser, encodeImage);
		}
	}
	
	private class SignUpTask extends AsyncTask<Object, Object, Object> {
		@Override
		protected Object doInBackground(final Object... urls) {
			CheckSignUp();
			return null;
		}

		@Override
		protected void onPostExecute(final Object result) {
			closeDialog();
			Log.i("SignUp", "Ket qua=" + String.valueOf(Post.this.result));
			if (Post.this.result <= 4)
				showMessage("Đăng kí thất bại", "Không được bỏ trống name, addres, phone, location ");			
			else if (Post.this.result == 5)
				showMessage("Đăng kí thất bại", "Số điện thoại không đúng..."
								+ "\n Bạn vui lòng nhập số điện thoại chính xác"
								+ "\n Chúng tôi sẽ không sử dụng số điện thoại của bạn với mục đích thương mại");	
		}

		@Override
		protected void onPreExecute() {
			showDialog();
		}
	}
}
